﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TaskTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Test_Task_1();
            // Test_Task_2();
            //ReferenceTask2();
            //var result = Test_Task_3();
            //Console.WriteLine(result);
            //RefernceTask4();

            //Test_Task_5();
            Test_Task_6();
        }

        //启动Task
        static void Test_Task_1()
        {
            Task.Run(() => { Console.WriteLine("Hello World"); });

        }

        static void ReferenceTask2()
        {
            Test_Task_2(out Task task);
            task.Wait();
            Console.WriteLine("主线程运行结束");
        }

        static void Test_Task_2(out Task out_Task)
        {
            out_Task = Task.Run(() =>
            {
                System.Threading.Thread.Sleep(5000);
                Console.WriteLine("子进行运行结束");
            });
        }


        static int Test_Task_3()
        {
            var task = Task.Run(() =>
            {

                System.Threading.Thread.Sleep(100);
                Console.WriteLine("我有返回的对象");
                return 3;
            });
            return task.Result;
        }

        static void RefernceTask4()
        {
            var result = Test_Task_4();
            Console.WriteLine("线程执行结束");
        }

        static int Test_Task_4()
        {
            Task<int> task = Task.Run(() =>
            {
                return Enumerable.Range(2, 3000000).Count(n =>
                                                     Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0));
            });
            Console.WriteLine("Task running...");
            Console.WriteLine("The answer is " + task.Result);
            return task.Result;
        }

        static void Test_Task_5()
        {
            Task<int> primeNumberTask = Task.Run(() =>
     Enumerable.Range(2, 3000000).Count(n =>
     Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0)));

            var awaiter = primeNumberTask.GetAwaiter();
            awaiter.OnCompleted(() =>
            {
                Console.WriteLine(awaiter.GetResult());       // Writes result
                Console.ReadLine();
            });
            Console.WriteLine("执行完成了,相应的操作");
            Console.ReadLine();


        }

        static void Test_Task_6()
        {
            Task<int> primeNumberTask = Task.Run(() =>
       Enumerable.Range(2, 3000000).Count(n =>
       Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0)));

            primeNumberTask.ContinueWith(antecedent =>
            {
                int result = antecedent.Result;
                Console.WriteLine(result);          // Writes 123
            });
            Console.WriteLine("执行完成了,相应的操作");
            Console.ReadLine();
        }

    }
}
